import os

from utils.namespace import Namespace
from utils.persist import save_to_pickle, load_from_pickle

from stacking.warehouse.warehouse import Warehouse
from stacking.instance.calendar import Calendar


class Instance(object):
    """An instance of the Stacking Problem consists of a warehouse state and a set of items."""
    pickle_protocol = 2
    
    def __init__(self, items, warehouse, **meta):
        self.calendar = Calendar(items)
        self.warehouse = warehouse
        self.warehouse.items = self.items
        self.meta = Namespace(meta)
        
    @property
    def items(self):
        return self.calendar.items
        
    @classmethod
    def quick_build(cls, items, nstacks, **meta):
        return cls(items, Warehouse.quick_build(id="Warehouse", nstacks=nstacks), **meta)
        
    @classmethod
    def load(cls, filepath):
        return load_from_pickle(filepath, cls.pickle_protocol)
        
    def save(self, filepath=None):
        if filepath is not None:
            filepath = os.path.abspath(filepath)
            directory, filename = os.path.split(filepath)
            self.meta.directory = directory
            self.meta.filename  = filename
            self.meta.filepath  = filepath
        elif "filepath" not in self.meta:
            raise Exception("output file path required")
        save_to_pickle(self, self.meta.filepath, self.pickle_protocol)
        
